var fs = require('fs');
var mongoose = require('mongoose');

var ModelManager = function(server, callback) {
	this.server = server;
	this.callback = callback;
	modelManager = this;

	fs.readFile('./Configuration/modelManager.json', function(e, content) {
		if (e)
			throw e;
		
		modelManager.config = JSON.parse(content);

		server.db = mongoose.createConnection('mongodb://' + modelManager.config.server
				+ ':' + modelManager.config.port + '/' + modelManager.config.database);

		if (typeof (modelManager.callback) == 'function') {
			modelManager.callback();
		}
	});

	server.Models = {};
	return this;
};

ModelManager.prototype.add = function(module) {
	var model = require(this.config.modelPath + '/' + module);
	if (!model.name || !model.schema)
		throw TypeError("ModelManager.add requires properties name and schema");

	this.server.Models[model.name] = server.db.model(model.name, model.schema);
	return this;
};

ModelManager.prototype.native = function() {
	return this.server.db.db;
};

module.exports = ModelManager;
